import fs from 'node:fs';
import { formatObject, PromiseQueue, createCallback } from '../common.js';

const nextJson = './next.json';

const jsonFile = './data.json';

const errorJson = './error.json';

const queue = new PromiseQueue();

// 读取JSON文件 参数：如果没有参数，返回所有。如果为true，返回有值的，如果为false返回无值的
export const read = (flag, json = jsonFile) => {
    return new Promise(resolve => {
        fs.readFile(json, 'utf8', (err, data) => {
            if (err) {
                console.error('Error reading file:', err);
                return;
            }
            try {
                const obj = JSON.parse((data || '{}').trim());
                if (typeof flag === 'boolean') {
                    const ent = Object.entries(obj);
                    const enta = flag ? ent.filter(item => item[1]) : ent.filter(item => !item[1]);
                    resolve(Object.fromEntries(enta));
                } else {
                    resolve(obj);
                }
            } catch (err) {
                resolve({});
            }
        });
    });
};

// 写入JSON文件
export const write = (obj = {}, json = jsonFile) => {
    return new Promise(resolve => {
        // 写入格式化的json
        //  const jsonContent = JSON.stringify(obj, null, 2);
        fs.writeFile(json, formatObject(obj), 'utf8', err => {
            if (!err) {
                resolve('success');
            } else {
                console.error('Error writing file:', err);
            }
        });
    });
};

// （修复error后）删除error属性
export const fixError = attr => {
    queue.enqueue(() => {
        return new Promise(resolve => {
            read(null, errorJson).then(obj => {
                const res = Reflect.deleteProperty(obj, attr);
                if (res) {
                    write({ ...obj }, errorJson).then(resolve);
                } else {
                    resolve(false);
                }
            });
        });
    });
};

// 写入error记录文件
export const writeError = (myObj = {}) => {
    queue.enqueue(() => {
        return new Promise(resolve => {
            read(null, errorJson).then(obj => {
                write({ ...obj, ...myObj }, errorJson).then(resolve);
            });
        });
    });
};

export const readNext = () => {
    return new Promise(resolve => {
        fs.readFile(nextJson, 'utf8', (err, data) => {
            if (err) {
                console.error('Error reading file:', err);
                return;
            }
            try {
                const obj = JSON.parse((data || '{}').trim());
                resolve(obj);
            } catch (err) {
                resolve({});
            }
        });
    });
};

export const writeNext = (obj = {}) => {
    return new Promise(resolve => {
        // 写入格式化的json
        // const jsonContent = JSON.stringify(obj, null, 2);
        fs.writeFile(nextJson, formatObject(obj), 'utf8', err => {
            if (!err) {
                resolve('next.json写入成功');
            } else {
                console.error('Error writing file:', err);
            }
        });
    });
};

const test = async () => {
    /*     setTimeout(async ()=>{
        const red = await read();
        console.log(red)
    },3000) */
    /*  const wa = [
        '0b9f8986ff56ae459d1232b61064357d',
        '3486444409fcbd4c069bc257d415cf93',
        '43314113943215beca6cf530f96a6cf2',
        '46f86728b3ec8761dae3be7c3de7bc22',
        '6e2d1ff607e5a76f817ee0273ce4cc39',
        '6f3c8e355b664dc0ccf7611172cc7b04',
        '98c5cc15c85ef5d835ec414775474072',
        '9f789e4adb9be9f498cc712015423be3',
        'a70c6c3c1923d15a3facfa547f8d7289',
        'd1dbb8608bbe3ff91bb0360fcca65f28'];

    const obj = Object.fromEntries(wa.map(key  => [key, ''])); 

    const rej = await write(obj)
    console.log(rej)
 */
    //  console.log(await read())
};
// test();
